<template>

  <el-form ref="form"
           :model="loginData"
           class="container"
           @submit.prevent="login"
           :rules="rules">
    <div class="wml" @click="changeToQrLogin">
      <svg width="72" height="72" viewBox="0 0 72 72" fill="none"
           xmlns="http://www.w3.org/2000/svg">
        <mask id="mask0_13456_28587" maskUnits="userSpaceOnUse" x="0" y="0" width="72" height="72"
              style="mask-type: alpha;">
          <path d="M0 0H64C68.4183 0 72 3.58172 72 8V72L0 0Z" fill="white"></path>
        </mask>
        <g mask="url(#mask0_13456_28587)">
          <path fill-rule="evenodd" clip-rule="evenodd"
                d="M14 10H5V15H14V10ZM17 10H34V15H17V10ZM37 10H62V35H37V10ZM41 14H58V31H41V14ZM54 18H45V27H54V18ZM17 18H34V35H17V18ZM20.6429 21.6429H30.3572V31.3572H20.6429V21.6429ZM27.9285 24.0714H23.0714V28.9286H27.9285V24.0714ZM26 38H37V46H26V38ZM40 38H45V43H40V38ZM62 54H57V72H62V54ZM48 38H62V43H48V38ZM62 46H57V51H62V46ZM54 46H41V59H54V46ZM50 50H45V55H50V50Z"
                fill="#7BA3FF"></path>
        </g>
      </svg>
      <el-text>
        扫码登录
      </el-text>

    </div>
    <el-form-item class="title">
      <el-text tag="b" size="large">账号登录</el-text>
    </el-form-item>
    <el-form-item prop="username"
                  :class="{ 'is-error': pwError }">
      <el-input style="margin-top: 20px"
                v-model="loginData.username"
                placeholder="请输入用户名"
                :class="{ 'error-border': pwError }"/>
    </el-form-item>
    <el-form-item prop="password"
                  :class="{ 'is-error': pwError }">
      <el-input v-model="loginData.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                :class="{ 'error-border': pwError }"
      >
        <template #suffix>
          <el-icon size="large" style="cursor: pointer" @click="togglePassword">
            <component :is="showPassword ? 'el-Hide' : 'el-View'"/>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item class="check-forget">
      <el-checkbox v-model="isChecked">
        7天内免登录
      </el-checkbox>
      <el-link type="default" underline="never">
        忘记密码?
      </el-link>
    </el-form-item>

    <el-form-item class="submit-btn">
      <el-button type="primary" @keyup.enter="login" @click="login">
        登 录
      </el-button>
    </el-form-item>
    <el-form-item class="extra-options">
      <el-link underline="never" @click="register">
        注册新账号
      </el-link>
      &nbsp;| &nbsp;
      <el-link underline="never" @click="changeToPhoneLogin">
        手机号登录
      </el-link>
    </el-form-item>
    <el-form-item>
      <el-link underline="never">
        阅读并接受《服务条款》和《隐私政策》
      </el-link>
    </el-form-item>
  </el-form>

</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import type {pwLoginForm} from "@/api/login/types.ts";
import {ElNotification, type FormInstance, type FormRules} from "element-plus";
import {pwLogin} from "@/api/login";
import {useRouter} from "vue-router";
import {useTokenStore} from "@/stores/useTokenStore.ts";

const showPassword = ref<boolean>(false)
const isChecked = ref<boolean>(false)
const loginData = reactive<pwLoginForm>({
  username: '',
  password: ''
})

const emit = defineEmits(["change-type"])

//切换到手机号登录
function changeToPhoneLogin() {
  emit('change-type', 1)
}

//切换到二维码登录
function changeToQrLogin() {
  emit('change-type', 2)
}

//注册账号
function register() {
  emit('change-type', 4)
}

//显示或者隐藏密码
function togglePassword() {
  showPassword.value = !showPassword.value
}

const form = ref<FormInstance>()
//校验规则
const rules = reactive<FormRules<pwLoginForm>>({
  username: [
    {required: true, message: "用户名不可为空", trigger: "blur"},
    {min: 6, max: 20, message: "用户名长度为6-20位", trigger: "blur"},
    {
      validator: (_, value, callback) => {
        if (!/^[a-zA-Z0-9_]{6,20}$/.test(value)) {
          callback(new Error("用户名格式错误:仅支持 数字 大小写字母和下划线"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  password: [
    {required: true, message: "密码不可为空", trigger: "blur"},
    {min: 6, max: 20, message: "密码长度为6-20位", trigger: "blur"},
    {
      validator: (_, value, callback) => {
        if (!/^[a-zA-Z0-9_]{6,20}$/.test(value)) {
          callback(new Error("密码格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
})

const router = useRouter();
const pwError = ref(false)

//登录
async function login() {

  await form.value?.validate((valid, fields) => {
    if (valid) {
      pwLogin(loginData).then((res) => {
        //存储token
        useTokenStore().setToken(res.data);
        //导航到首页
        router.push('/')
        ElNotification.success({
          title: 'Hi~',
          message: `${useTokenStore().username}欢迎回来`,
          duration: 2000
        })
      }).catch(() => {
        pwError.value = true;
      })

    } else {
      console.log('错误注册校验!', fields)
      pwError.value = true;
    }
  })
}
</script>

<style scoped lang="scss">
.container {
  display: flex;
  align-items: center;
  flex-direction: column;

  //扫码svg
  .wml {
    cursor: pointer;
    height: 72px;
    position: absolute;
    right: 0;
    top: 0;
    width: 72px;
    z-index: 2;


    .el-text {
      position: absolute;
      padding: 6px 8px;
      right: 72px;
      top: 10px;
      background-color: #4573f6;
      color: #fff;
      font-weight: 400;
      line-height: 20px;
      white-space: nowrap;
      border-radius: 2px;
      opacity: 0;

      // 新增箭头样式
      &::after {
        content: "";
        position: absolute;
        right: -8px; // 从文字框右侧伸出
        top: 50%;
        transform: translateY(-50%);
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 6px 0 6px 8px; // 控制箭头大小和方向
        border-color: transparent transparent transparent #4573f6; // 箭头颜色与背景一致
      }


    }

    &:hover .el-text {
      opacity: 1;
      transition: opacity 0.3s ease-in-out;
    }


  }

  //标题
  .title {
    padding-top: 25px;

    .el-text {
      font-size: 24px;
      --el-text-color: $base-color-text-primary;
    }
  }

  //输入框
  .el-input {
    width: 340px;
    height: 48px;
    --el-text-color-placeholder: #585e6d;
    font-size: 16px;

    border-radius: 6px;

    :deep(.el-input__wrapper) {
      padding-left: 20px;
    }

    :deep(.el-input .error-border) {
      .el-input__wrapper {
        box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;

        &:hover {
          box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
        }
      }
    }
  }

  //勾选及忘记密码
  .check-forget {
    width: 95%;

    :deep( .el-form-item__content) {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }

  }

  //登录按钮
  .submit-btn {
    margin-top: 25px;

    .el-button {
      font-size: 20px;
      width: 352px;
      height: 48px;
      background-color: #3370ff;
    }
  }

  //额外选项
  .extra-options {
    margin-top: -10px;
  }
}
</style>
